package com.pi.shisan.service.service.impl;

import com.pi.shisan.service.domain.LedDndModeSetting;
import com.pi.shisan.service.dto.LedDndModeSettingDTO;
import com.pi.shisan.service.mapper.LedDndModeSettingMapper;
import com.pi.shisan.service.service.LedDndModeSettingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Objects;

@Service
public class LedDndModeSettingServiceImpl implements LedDndModeSettingService {

    @Autowired
    private LedDndModeSettingMapper ledDndModeSettingMapper;

    @Override
    public synchronized void updateMode(LedDndModeSettingDTO param) {
        LedDndModeSetting ledDndModeSetting = ledDndModeSettingMapper.selectOneByType(param.getDndType());
        if (ledDndModeSetting == null) {
            ledDndModeSetting = new LedDndModeSetting();
            ledDndModeSetting.setDndType(param.getDndType());
        }
        ledDndModeSetting.setDndStartTime(param.getDndStartTime());
        ledDndModeSetting.setDndEndTime(param.getDndEndTime());
        if (ledDndModeSetting.getId() == null) {
            ledDndModeSettingMapper.insert(ledDndModeSetting);
        } else {
            ledDndModeSettingMapper.updateById(ledDndModeSetting);
        }
    }

    @Override
    public void clearMode(Integer type) {
        ledDndModeSettingMapper.clearByType(type);
    }

    @Override
    public LedDndModeSettingDTO getSettingByType(Integer type) {
        LedDndModeSetting ledDndModeSetting = ledDndModeSettingMapper.selectOneByType(type);
        if (ledDndModeSetting == null) {
            return null;
        }
        LedDndModeSettingDTO ledDndModeSettingDTO = new LedDndModeSettingDTO();
        BeanUtils.copyProperties(ledDndModeSetting, ledDndModeSettingDTO);
        return ledDndModeSettingDTO;
    }

    @Override
    public boolean checkIsInDnd(LedDndModeSettingDTO param, LocalDateTime now) {
        if (param == null || param.getDndStartTime() == null || param.getDndEndTime() == null) {
            return false;
        }
        if (Objects.equals(param.getDndStartTime(), param.getDndEndTime())) {
            return true;
        }
        LocalTime localTime = now.toLocalTime();
        int minute = localTime.getHour() * 60 + localTime.getMinute();
        int start = param.getDndStartTime();
        int end = param.getDndEndTime();
        if (end < start) {
            if (minute < end) {
                minute += 1440;
            }
            end += 1440;
        }
        return minute >= start && minute <= end;
    }

}
